import dsBridge from "dsbridge";

export class FetchFileAndroidLoader {
  static init(): void {
    System.constructor.prototype.shouldFetch = function () {
      return true;
    };

    System.constructor.prototype.fetch = async (url) => {
      if (url.startsWith("file:")) {
        try {
          const source = await new Promise<string>((resolve) => {
            dsBridge.call(
              "FILE.readLocalFile",
              {
                path: url,
              },
              function (ret) {
                const { data } = JSON.parse(ret);
                resolve(data);
              }
            );
          });
          return {
            ok: true,
            status: 200,
            headers: {
              get(headerName) {
                if (headerName === "content-type") {
                  return "application/javascript";
                } else {
                  throw Error(
                    `NodeJS fetch emulation doesn't support ${headerName} header`
                  );
                }
              },
            },
            async text() {
              return source;
            },
            async json() {
              return JSON.parse(source);
            },
          };
        } catch (e) {
          if (e.code === "ENOENT")
            return { status: 404, statusText: e.toString() };
          else return { status: 500, statusText: e.toString() };
        }
      } else {
        return fetch(url);
      }
    };
  }
}
